package com.tungse.study.rpc.framework.register;

import com.tungse.study.rpc.framework.entity.RpcUri;

import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Tungse
 */
public class RemoteMapRegister {

    private static Map<String, List<RpcUri>> URIS_REGISTER = new ConcurrentHashMap<>();

    public static void register(String serviceName, RpcUri rpcUri) {

        if(URIS_REGISTER.containsKey(serviceName)) {
            URIS_REGISTER.get(serviceName).add(rpcUri);
        } else {
            URIS_REGISTER.put(serviceName, new ArrayList<>(Collections.singletonList(rpcUri)));
        }
        saveFile();
    }

    public static List<RpcUri> getServiceUri(String serviceName) {
        readFile();
        return URIS_REGISTER.get(serviceName);
    }

    private static void saveFile() {
        //保存到文件
        try {
            FileOutputStream  fos = new FileOutputStream(RemoteMapRegister.class.getClassLoader().getResource("tempUri.txt").getPath());
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(URIS_REGISTER);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void readFile() {
        //保存到文件
        try {
            FileInputStream fos = new FileInputStream(RemoteMapRegister.class.getClassLoader().getResource("tempUri.txt").getPath());
            ObjectInputStream ois = new ObjectInputStream(fos);
            URIS_REGISTER = (Map<String, List<RpcUri>>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
